package com.deke.order.service.Impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.deke.entity.EduCourse;
import com.deke.entity.EduTeacher;
import com.deke.entity.Order;
import com.deke.entity.TbMember;
import com.deke.order.dao.CourseDao;
import com.deke.order.dao.OrderDao;
import com.deke.order.service.QianOrderPayService;
import com.deke.order.utils.HttpClient;
import com.deke.vo.Result;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Username 刘亦辰（59372312@qq.com）
 * @date ：Created in 2023/1/11 13:04
 * @description：
 * @modified By：
 * @version:
 **/
@Service
public class QianOrderPayServiceImpl implements QianOrderPayService {
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private CourseDao courseDao;

    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.mch_id}")
    private String mch_id;
    @Value("${weixin.api_key}")
    private String api_key;
    /**
     * @create by: Username 刘亦辰 
     * @description: 新生成订单 
     * @create time: 2023/1/11 13:07
     * @param null 
     * @return :  
     **/
    @Override
    public Result createWeiXin(String id, String huiYuanId) {
        //先查询该用户是否已经购买该课程
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",id);
        wrapper.eq("member_id",huiYuanId);
        Order order = orderDao.selectOne(wrapper);
        //1.订单不为空 证明已经下过单了
        if (ObjectUtil.isNotEmpty(order)){
            if (order.getStatus()==0){
                return new Result(5000,"该订单已创建,请先支付",null);
            }
            return new Result(5000,"该订单已完成支付,无需支付",null);
        }
        // 2.根据课程编号查询详情 并创建订单
        EduCourse eduCourse = courseDao.selectById(id);
        TbMember member = courseDao.getMember(huiYuanId);
        EduTeacher teacher = courseDao.getTeacher(eduCourse.getTeacherId());
        // 3. 保存订单
        Order newOrder= new Order();
        newOrder.setOrderNo(IdUtil.getSnowflakeNextIdStr()+"");//订单号
        newOrder.setCourseId(id);
        newOrder.setCourseTitle(eduCourse.getTitle());
        newOrder.setCourseCover(eduCourse.getCover());
        newOrder.setTeacherName(teacher.getName());
        newOrder.setNickname(member.getNickname());
        newOrder.setMobile(member.getMobile());
        newOrder.setMemberId(huiYuanId);
        newOrder.setTotalFee(eduCourse.getPrice().doubleValue());
        newOrder.setPayType(0);//支付类型
        newOrder.setStatus(0);//支付状态
        newOrder.setIsDeleted(0+"");
        newOrder.setGmtCreate(LocalDateTime.now());
        newOrder.setGmtModified(LocalDateTime.now());
        int row = orderDao.insert(newOrder);
        if (row > 0 ){
            try {
                // 下单成功 调用微信客户端生成二维码
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                httpClient.setHttps(true);
                // 微信接口需要的参数
                Map<String, String> params = new HashMap<>();
                params.put("appid", appid);
                params.put("mch_id", mch_id);
                params.put("nonce_str", WXPayUtil.generateNonceStr());
                params.put("body", newOrder.getCourseTitle());
                params.put("out_trade_no", newOrder.getOrderNo());
                params.put("total_fee",new BigDecimal(0.01).multiply(new BigDecimal(100)).intValue() + "");
                params.put("spbill_create_ip", "127.0.0.1");//该地址未来应该是你项目部署服务器的ip
                params.put("notify_url", "http://localhost:8001/order/back");//通知地址
                params.put("trade_type", "NATIVE");//扫描支付
                //因为微信接口需要的参数格式为xml格式的字符串。
                httpClient.setXmlParam(WXPayUtil.generateSignedXml(params,api_key));
                //执行请求
                httpClient.post();
                //获取请求后响应的结果
                String content = httpClient.getContent();
                //把xml格式的字符串转化为map对象
                Map<String, String> map = WXPayUtil.xmlToMap(content);
                if("SUCCESS".equals(map.get("result_code"))){
                    Map<String,Object> result=new HashMap<>();
                    result.put("total",newOrder.getTotalFee());
                    result.put("code_url",map.get("code_url"));
                    result.put("out_trade_no",newOrder.getOrderNo());
                    return new Result(2000,"生成二维码",result);
                }
                return new Result(5000,"生成二维码失败",null);
            }catch (Exception e){
                return new Result(5000,"生成二维码失败",null);
            }
        }else {
            return new Result(5000,"下单失败" );
        }
    }

    @Override
    public Result createWeiXin1(String id, String huiYuanId) {
        //先查询该用户是否已经购买该课程
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",id);
        wrapper.eq("member_id",huiYuanId);
        Order order = orderDao.selectOne(wrapper);
        System.out.println(order);
        //1.订单不为空 证明已经下过单了
        System.out.println("1111111111");
            try {
                System.out.println("22222222222");
                // 下单成功 调用微信客户端生成二维码
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                httpClient.setHttps(true);
                // 微信接口需要的参数
                Map<String, String> params = new HashMap<>();
                params.put("appid", appid);
                params.put("mch_id", mch_id);
                params.put("nonce_str", WXPayUtil.generateNonceStr());
                params.put("body", order.getCourseTitle());
                params.put("out_trade_no", order.getOrderNo());
                params.put("total_fee",new BigDecimal(0.01).multiply(new BigDecimal(100)).intValue() + "");
                params.put("spbill_create_ip", "127.0.0.1");//该地址未来应该是你项目部署服务器的ip
                params.put("notify_url", "http://localhost:8001/order/back");//通知地址
                params.put("trade_type", "NATIVE");//扫描支付
                //因为微信接口需要的参数格式为xml格式的字符串。
                httpClient.setXmlParam(WXPayUtil.generateSignedXml(params,api_key));
                //执行请求
                httpClient.post();
                //获取请求后响应的结果
                System.out.println("33333333333333");
                String content = httpClient.getContent();
                System.out.println(content);
                //把xml格式的字符串转化为map对象
                Map<String, String> map = WXPayUtil.xmlToMap(content);
                if("SUCCESS".equals(map.get("result_code"))){
                    Map<String,Object> result=new HashMap<>();
                    result.put("total",order.getTotalFee());
                    result.put("code_url",map.get("code_url"));
                    result.put("out_trade_no",order.getOrderNo());
                    return new Result(2000,"生成二维码",result);
                }
                return new Result(5000,"生成二维码失败",null);
            }catch (Exception e){
                return new Result(5000,"生成二维码失败",null);
            }

    }

    /**
     * @create by: Username 刘亦辰 
     * @description: 查询订单状态 
     * @create time: 2023/1/11 16:19
     * @param null 
     * @return :  
     **/
    @Override
    public Result getPayStatus(String out_trade_no) {
        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            // 微信接口需要的参数
            Map<String, String> params = new HashMap<>();
            params.put("appid", appid);
            params.put("mch_id", mch_id);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            params.put("out_trade_no",out_trade_no);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(params,api_key));
            //发送请求
            httpClient.post();
            String content = httpClient.getContent();
            System.out.println(content);
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if (map.get("trade_state").equals("SUCCESS")) {
                //1.修改订单的状态。
                Order order = new Order();
                order.setStatus(1);
                order.setGmtModified(LocalDateTime.now());
                UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
                wrapper.eq("order_no",out_trade_no);
                orderDao.update(order, wrapper);
                //2. 保存支付记录。
                return new Result(2000,"支付成功",null);
            }else if(map.get("trade_state").equals("NOTPAY")){
                return new Result(2001,"未支付请及时支付",null);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(5000,"订单支付失败",null);
    }
}